<template>
  <div id="container">
    <h1>Qiankun Main <a href="/">/</a></h1>
    <header>
      <nav>
        <ol>
          <li v-for="app of apps" :key="app.name">
            <a @click="goto(app.name, `${app.activeRule}`)">{{ app.name }}</a>
          </li>
        </ol>
      </nav>
    </header>
    <div id="appContainer"></div>
    <div id="sidebarContainer"></div>
  </div>
</template>

<script>
import {
  registerMicroApps,
  runAfterFirstMounted,
  setDefaultMountApp,
  start,
  loadMicroApp
} from 'qiankun'
import {
  modules,
  formatQiankunApps,
  getEntry
} from './enum/modules'

const apps = formatQiankunApps(modules)

export default {
  name: 'master',
  data() {
    return {
      apps
    }
  },
  created() {
    if (!window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__) {
      this.initQiankun()
    } else {
      // fix hot-reload
      location.reload()
    }
  },
  methods: {
    goto(title, href) {
      window.history.pushState({}, title, href)
    },
    initQiankun() {
      registerMicroApps(
          this.apps,
          /*{
            beforeLoad: [
              app => {
                console.log('before load', app)
              }
            ],
            beforeMount: [
              app => {
                console.log('before mount', app)
              }
            ],
            afterUnmount: [
              app => {
                console.log('after unload', app)
              }
            ]
          }*/
      )

      setDefaultMountApp(apps[0].name)

      runAfterFirstMounted(() => {
        console.info('first app mounted')
      })

      start({prefetch: true})

      loadMicroApp({
        name: 'sidebar',
        activeRule: '/',
        entry: getEntry({devPort: 8083, moduleName: 'sidebar'}),
        container: '#sidebarContainer'
      })
    }
  }
}
</script>

<style scoped>
a {
  color: #42b983;
  cursor: pointer;
}

#appContainer {
  margin-top: 50px;
}

#sidebarContainer {
  position: fixed;
  right: 0;
  top: 0;
  border: 1px solid #ccc;
  width: 300px;
  height: 100px;
  overflow: auto;
}
</style>
